package com.flower.service.impl;

import com.flower.domain.ApiResult;
import com.flower.mapper.BackageUserMapper;
import com.flower.service.UploadService;
import com.flower.utils.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {

    @Resource
    private BackageUserMapper backageUserMapper;

    @Override
    public ApiResult<String> uploadFile(MultipartFile file) {
        //TODO 判断文件类型
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //对原始文件名进行判断
//        if (!originalFilename.endsWith(".jpg")) {
//            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
//        }
        //如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(file, filePath);
        //上传文件后 修改数据库用户头像地址
//        BackageUser backageUser = new BackageUser();
//        backageUser.setAvater(url);
//        backageUser.setId(SecurityUtils.getUserId());
//        backageUserMapper.updateById(backageUser);
        return ApiResult.ok(url);
    }

    private String accessKey;
    private String secretKey;
    private String bucket;

    /**
     * 七牛云文件上传 方法
     */
    private String uploadOss(MultipartFile imgFile, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
//                http://rej3bt7sl.bkt.clouddn.com/2022/07/05/bd3baa6fabf24d6ba0175bfaf4c38da4.jpg
                return "http://lixinghe.meimeng.eu.org/" + key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }

            }
        } catch (Exception ex) {
            //ignore
        }
        return "sad";
    }

    /**
     * 通过key删除七牛云上的图片
     * key为不加域名的在七牛云中的图片的名称
     * 如：http://qlwdwvwug.hn-bkt.clouddn.com/33_20212604132639.jpg
     * key为 33_20212604132639.jpg
     */
    public void deleteFile(String key){
        //创建凭证
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, new Configuration());
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}
